﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DCTAccess.Business;
using DCTLib.Common;
using DCTAccess.Business.Location;

public partial class AdminZone_LocationManagement : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
            LoadLocation();
        }
    }

    protected void BindData()
    {
        DataTable dtLocation = LocationController.GetListLocation();
        gvLocation.DataSource = dtLocation;
        gvLocation.DataBind();
    }

    private void LoadLocation()
    {
        ControlLoader.LoadDropDownList(this.ddlRegion, LocationController.GetLocationDetails(), "LocationID", "LocationName");
        this.ddlRegion.Items.Insert(0, new ListItem("Select a Location", "0"));
    }

    protected void gvLocation_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        ControlLoader.BindDatagrid(gvLocation, LocationController.GetListLocation(), e.NewPageIndex);
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        //Nothing to do 
    }

    private bool ValidateSaveChangeData()
    {
        bool validated = true;
        if (ValidationHelper.IsEmpty(txtLocation))
        {
            lblError.Text = AppMessages.RequireField("Location Name") + "<br>";
            validated = false;
        }
        return validated;
    }

    private Location GetLocation()
    {
        Location local = new Location();
        local.LocationName = txtLocation.Text;
        local.IsEnable = cbxAction.Checked;
        if (this.ddlRegion.Items.Count > 0 && this.ddlRegion.SelectedValue.Length > 0)
            local.ParentID = int.Parse(this.ddlRegion.SelectedValue);
        return local;
    }

    private void ClearData()
    {
        txtLocation.Text = "";
        cbxAction.Checked = false;
        LoadLocation();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (ValidateSaveChangeData())
        {
            Location local = GetLocation();

            if (LocationController.Insert(local))
            {
                lblError.Text = AppMessages.INSERT_SUCCESSFULLY;
                BindData();
                ClearData();
            }
            else
            {
                lblError.Text = AppMessages.CANNOT_INSERT_VI;
                ClearData();
            }
        }
    }
}
